<template>
  <div class="activity-audit">
    <el-container>
      <el-header class="audit-header">
        <div class="header-content">
          <h2>活动报名审核</h2>
          <div class="header-actions">
            <el-button @click="refreshData">刷新数据</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </el-header>
      
      <el-main class="audit-main">
        <!-- 活动选择 -->
        <el-card class="activity-selector" shadow="never">
          <template #header>
            <div class="card-header">
              <span>选择要审核的活动</span>
            </div>
          </template>
          
          <el-table
            :data="activityList"
            v-loading="activityLoading"
            stripe
            @row-click="selectActivity"
            style="width: 100%"
          >
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="name" label="活动名称" min-width="150" />
            <el-table-column prop="location" label="活动地点" width="120" />
            <el-table-column prop="points" label="活动积分" width="100">
              <template #default="{ row }">
                <span class="points">{{ row.points || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="startTime" label="开始时间" width="150">
              <template #default="{ row }">
                {{ formatDateTime(row.startTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="endTime" label="结束时间" width="150">
              <template #default="{ row }">
                {{ formatDateTime(row.endTime) }}
              </template>
            </el-table-column>
            <el-table-column label="报名情况" width="120">
              <template #default="{ row }">
                <el-tag type="info" size="small">
                  {{ getRegistrationCount(row.id) }} 人报名
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="selectActivity(row)"
                >
                  审核报名
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 报名审核区域 -->
        <el-card 
          v-if="selectedActivity" 
          class="audit-area" 
          shadow="never"
        >
          <template #header>
            <div class="card-header">
              <div class="activity-info">
                <h3>{{ selectedActivity.name }} - 报名审核</h3>
                <p>地点：{{ selectedActivity.location }} | 积分：{{ selectedActivity.points }} | 
                   时间：{{ formatDateTime(selectedActivity.startTime) }} - {{ formatDateTime(selectedActivity.endTime) }}</p>
              </div>
              <div class="batch-actions">
                <el-button 
                  type="success" 
                  :disabled="!selectedRegistrations.length"
                  @click="showBatchApproveDialog"
                >
                  批量审核 ({{ selectedRegistrations.length }})
                </el-button>
                <el-button @click="loadRegistrations">刷新列表</el-button>
              </div>
            </div>
          </template>

          <!-- 报名医生列表 -->
          <el-table
            :data="registrationsList"
            @selection-change="handleSelectionChange"
            v-loading="registrationsLoading"
            border
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="doctorName" label="医生姓名" width="120" />
            <el-table-column prop="hospitalName" label="医院名称" width="150" />
            <el-table-column prop="practiceScope" label="执业范围" width="120" />
            <el-table-column prop="registrationTime" label="报名时间" width="160">
              <template #default="{ row }">
                {{ formatDateTime(row.registrationTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag 
                  :type="getStatusType(row.status)"
                  size="small"
                >
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="pointsEarned" label="获得积分" width="100">
              <template #default="{ row }">
                <span class="points">{{ row.pointsEarned || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <div v-if="row.status === 'REGISTERED' || row.status === 'ATTENDED'" class="action-buttons">
                  <el-button 
                    type="success" 
                    size="small" 
                    @click="showApproveDialog(row)"
                  >
                    审核
                  </el-button>
                </div>
                <span v-else-if="row.status === 'COMPLETED'" class="completed-tag">
                  <el-tag type="success" size="small">已完成</el-tag>
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            v-if="registrationsTotal > 0"
            v-model:current-page="registrationsCurrentPage"
            v-model:page-size="registrationsPageSize"
            :total="registrationsTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            style="margin-top: 20px; text-align: right;"
          />
        </el-card>
      </el-main>
    </el-container>

    <!-- 单个审核对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      title="审核医生报名"
      width="500px"
    >
      <div class="approve-content">
        <div class="doctor-info">
          <h4>医生信息</h4>
          <p><strong>姓名：</strong>{{ selectedRegistration?.doctorName }}</p>
          <p><strong>医院：</strong>{{ selectedRegistration?.hospitalName }}</p>
          <p><strong>执业范围：</strong>{{ selectedRegistration?.practiceScope }}</p>
          <p><strong>报名时间：</strong>{{ formatDateTime(selectedRegistration?.registrationTime) }}</p>
          <p v-if="selectedRegistration?.remark"><strong>备注：</strong>{{ selectedRegistration.remark }}</p>
        </div>

        <div class="activity-info">
          <h4>活动信息</h4>
          <p><strong>活动：</strong>{{ selectedActivity?.name }}</p>
          <p><strong>预设积分：</strong><span class="points">{{ selectedActivity?.points || 0 }} 分</span></p>
        </div>

        <el-form :model="approveForm" :rules="approveRules" ref="approveFormRef">
          <el-form-item label="审核状态" prop="status">
            <el-select v-model="approveForm.status" placeholder="请选择状态">
              <el-option label="已参加" value="ATTENDED" />
              <el-option label="已完成" value="COMPLETED" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="给予积分" prop="pointsEarned">
            <el-input-number 
              v-model="approveForm.pointsEarned" 
              :min="0" 
              :max="1000" 
              controls-position="right"
              placeholder="请输入积分"
              style="width: 200px"
            />
            <span style="margin-left: 10px; color: #909399; font-size: 12px;">
              建议：{{ selectedActivity?.points || 0 }} 分
            </span>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmApprove"
            :loading="approveLoading"
          >
            确认审核
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量审核对话框 -->
    <el-dialog
      v-model="batchApproveDialogVisible"
      title="批量审核报名"
      width="500px"
    >
      <div class="batch-approve-content">
        <div class="batch-info">
          <h4>批量审核信息</h4>
          <p><strong>活动：</strong>{{ selectedActivity?.name }}</p>
          <p><strong>选中医生：</strong>{{ selectedRegistrations.length }} 人</p>
          <p><strong>活动积分：</strong><span class="points">{{ selectedActivity?.points || 0 }} 分</span></p>
        </div>
        
        <el-form :model="batchApproveForm" :rules="batchApproveRules" ref="batchApproveFormRef">
          <el-form-item label="审核状态" prop="status">
            <el-select v-model="batchApproveForm.status" placeholder="请选择状态">
              <el-option label="已参加" value="ATTENDED" />
              <el-option label="已完成" value="COMPLETED" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="给予积分" prop="pointsEarned">
            <el-input-number 
              v-model="batchApproveForm.pointsEarned" 
              :min="0" 
              :max="1000" 
              controls-position="right"
              placeholder="请输入积分"
              style="width: 200px"
            />
            <span style="margin-left: 10px; color: #909399; font-size: 12px;">
              每人将获得此积分
            </span>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchApproveDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmBatchApprove"
            :loading="batchApproveLoading"
          >
            确认批量审核
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAdminActivityList 
} from '@/api/activity'
import { 
  getDoctorRegistrationsByActivity,
  approveDoctorRegistration,
  batchApproveDoctorRegistrations
} from '@/api/admin'

export default {
  name: 'ActivityAudit',
  setup() {
    const router = useRouter()
    
    // 活动列表
    const activityList = ref([])
    const activityLoading = ref(false)
    const selectedActivity = ref(null)
    
    // 报名列表
    const registrationsList = ref([])
    const registrationsLoading = ref(false)
    const selectedRegistrations = ref([])
    const registrationsCurrentPage = ref(1)
    const registrationsPageSize = ref(10)
    const registrationsTotal = ref(0)
    
    // 报名统计
    const registrationCounts = ref({})
    
    // 审核对话框
    const approveDialogVisible = ref(false)
    const approveLoading = ref(false)
    const selectedRegistration = ref(null)
    const approveFormRef = ref(null)
    
    const batchApproveDialogVisible = ref(false)
    const batchApproveLoading = ref(false)
    const batchApproveFormRef = ref(null)
    
    // 表单数据
    const approveForm = reactive({
      status: '',
      pointsEarned: 0
    })
    
    const batchApproveForm = reactive({
      status: '',
      pointsEarned: 0
    })
    
    // 表单验证规则
    const approveRules = {
      status: [
        { required: true, message: '请选择审核状态', trigger: 'change' }
      ],
      pointsEarned: [
        { required: true, message: '请输入积分', trigger: 'blur' },
        { type: 'number', min: 0, message: '积分不能小于0', trigger: 'blur' }
      ]
    }
    
    const batchApproveRules = {
      status: [
        { required: true, message: '请选择审核状态', trigger: 'change' }
      ],
      pointsEarned: [
        { required: true, message: '请输入积分', trigger: 'blur' },
        { type: 'number', min: 0, message: '积分不能小于0', trigger: 'blur' }
      ]
    }
    
    // 加载活动列表
    const loadActivityList = async () => {
      activityLoading.value = true
      try {
        const response = await getAdminActivityList()
        if (response.code === 200) {
          activityList.value = response.data || []
          // 加载每个活动的报名统计
          loadRegistrationCounts()
        } else {
          ElMessage.error(response.message || '获取活动列表失败')
        }
      } catch (error) {
        console.error('获取活动列表失败:', error)
        ElMessage.error('获取活动列表失败')
      } finally {
        activityLoading.value = false
      }
    }
    
    // 加载报名统计
    const loadRegistrationCounts = async () => {
      for (const activity of activityList.value) {
        try {
          const response = await getDoctorRegistrationsByActivity(activity.id, { current: 1, size: 1 })
          if (response.code === 200) {
            registrationCounts.value[activity.id] = response.data.total || 0
          }
        } catch (error) {
          console.error(`获取活动 ${activity.id} 报名统计失败:`, error)
        }
      }
    }
    
    // 获取报名人数
    const getRegistrationCount = (activityId) => {
      return registrationCounts.value[activityId] || 0
    }
    
    // 选择活动
    const selectActivity = async (activity) => {
      selectedActivity.value = activity
      selectedRegistrations.value = []
      registrationsCurrentPage.value = 1
      await loadRegistrations()
    }
    
    // 加载报名列表
    const loadRegistrations = async () => {
      if (!selectedActivity.value) return
      
      registrationsLoading.value = true
      try {
        const params = {
          current: registrationsCurrentPage.value,
          size: registrationsPageSize.value
        }
        
        const response = await getDoctorRegistrationsByActivity(selectedActivity.value.id, params)
        
        if (response.code === 200) {
          registrationsList.value = response.data.records || []
          registrationsTotal.value = response.data.total || 0
        } else {
          ElMessage.error(response.message || '获取报名列表失败')
        }
      } catch (error) {
        console.error('获取报名列表失败:', error)
        ElMessage.error('获取报名列表失败')
      } finally {
        registrationsLoading.value = false
      }
    }
    
    // 处理选择变化
    const handleSelectionChange = (selections) => {
      selectedRegistrations.value = selections
    }
    
    // 快速审核
    const quickApprove = async (registration, status) => {
      try {
        const response = await approveDoctorRegistration(registration.id, {
          status: status,
          pointsEarned: 0
        })
        
        if (response.code === 200) {
          ElMessage.success('操作成功!')
          await loadRegistrations()
          loadRegistrationCounts()
        } else {
          ElMessage.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
    
    // 显示审核对话框
    const showApproveDialog = (registration) => {
      selectedRegistration.value = registration
      approveForm.status = registration.status === 'REGISTERED' ? 'ATTENDED' : 'COMPLETED'
      approveForm.pointsEarned = selectedActivity.value?.points || 50
      approveDialogVisible.value = true
    }
    
    // 确认审核
    const confirmApprove = async () => {
      if (!approveFormRef.value) return
      
      await approveFormRef.value.validate(async (valid) => {
        if (!valid) return
        
        approveLoading.value = true
        try {
          const response = await approveDoctorRegistration(selectedRegistration.value.id, {
            status: approveForm.status,
            pointsEarned: approveForm.pointsEarned
          })
          
          if (response.code === 200) {
            ElMessage.success('审核成功!')
            approveDialogVisible.value = false
            await loadRegistrations()
            loadRegistrationCounts()
          } else {
            ElMessage.error(response.message || '审核失败')
          }
        } catch (error) {
          console.error('审核失败:', error)
          ElMessage.error('审核失败')
        } finally {
          approveLoading.value = false
        }
      })
    }
    
    // 显示批量审核对话框
    const showBatchApproveDialog = () => {
      if (selectedRegistrations.value.length === 0) {
        ElMessage.warning('请先选择要审核的报名记录')
        return
      }
      
      batchApproveForm.status = 'COMPLETED'
      batchApproveForm.pointsEarned = selectedActivity.value?.points || 50
      batchApproveDialogVisible.value = true
    }
    
    // 确认批量审核
    const confirmBatchApprove = async () => {
      if (!batchApproveFormRef.value) return
      
      await batchApproveFormRef.value.validate(async (valid) => {
        if (!valid) return
        
        batchApproveLoading.value = true
        try {
          const registrationIds = selectedRegistrations.value.map(item => item.id)
          
          const response = await batchApproveDoctorRegistrations({
            registrationIds: registrationIds,
            status: batchApproveForm.status,
            pointsEarned: batchApproveForm.pointsEarned
          })
          
          if (response.code === 200) {
            ElMessage.success('批量审核成功!')
            batchApproveDialogVisible.value = false
            await loadRegistrations()
            loadRegistrationCounts()
          } else {
            ElMessage.error(response.message || '批量审核失败')
          }
        } catch (error) {
          console.error('批量审核失败:', error)
          ElMessage.error('批量审核失败')
        } finally {
          batchApproveLoading.value = false
        }
      })
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      registrationsPageSize.value = size
      loadRegistrations()
    }
    
    const handleCurrentChange = (page) => {
      registrationsCurrentPage.value = page
      loadRegistrations()
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'REGISTERED': 'info',
        'ATTENDED': 'warning',
        'COMPLETED': 'success',
        'CANCELLED': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'REGISTERED': '已报名',
        'ATTENDED': '已参加',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    // 刷新数据
    const refreshData = () => {
      loadActivityList()
      if (selectedActivity.value) {
        loadRegistrations()
      }
    }
    
    // 返回
    const goBack = () => {
      router.go(-1)
    }
    
    onMounted(() => {
      loadActivityList()
    })
    
    return {
      activityList,
      activityLoading,
      selectedActivity,
      registrationsList,
      registrationsLoading,
      selectedRegistrations,
      registrationsCurrentPage,
      registrationsPageSize,
      registrationsTotal,
      approveDialogVisible,
      approveLoading,
      selectedRegistration,
      approveFormRef,
      batchApproveDialogVisible,
      batchApproveLoading,
      batchApproveFormRef,
      approveForm,
      batchApproveForm,
      approveRules,
      batchApproveRules,
      getRegistrationCount,
      selectActivity,
      loadRegistrations,
      handleSelectionChange,
      quickApprove,
      showApproveDialog,
      confirmApprove,
      showBatchApproveDialog,
      confirmBatchApprove,
      handleSizeChange,
      handleCurrentChange,
      formatDateTime,
      getStatusType,
      getStatusText,
      refreshData,
      goBack
    }
  }
}
</script>

<style scoped>
.activity-audit {
  height: 100vh;
  background-color: #f5f5f5;
}

.audit-header {
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 0;
}

.header-content {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.audit-main {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.activity-selector {
  background: white;
}

.audit-area {
  background: white;
  flex: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.activity-info h3 {
  margin: 0 0 5px 0;
  color: #409eff;
}

.activity-info p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.batch-actions {
  display: flex;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.action-buttons .el-button {
  padding: 5px 8px;
}

.completed-tag {
  display: flex;
  justify-content: center;
}

.approve-content, .batch-approve-content {
  padding: 0;
}

.doctor-info, .activity-info, .batch-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.doctor-info h4, .activity-info h4, .batch-info h4 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 16px;
}

.doctor-info p, .activity-info p, .batch-info p {
  margin: 5px 0;
  color: #606266;
}

.points {
  color: #f56c6c;
  font-weight: bold;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table .cell) {
  word-break: break-word;
}

:deep(.el-card__header) {
  background: #fafafa;
  border-bottom: 1px solid #ebeef5;
}
</style>
